import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'joke_bloc.dart';

class HomeView extends StatelessWidget {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Random Joke Generator (Bloc)')),
      body: SizedBox.expand(
        child: BlocBuilder<JokeBloc, JokeState>(
          builder: (context, state) {
            return Stack(
              alignment: Alignment.center,
              children: [
                // 显示刷新进度条
                if (state is JokeRefreshing)
                  const Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: LinearProgressIndicator(),
                  ),

                // 根据状态显示不同内容
                switch (state) {
                  JokeLoaded() => SelectableText(
                      '${state.joke.setup}\n\n${state.joke.punchline}',
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 24),
                    ),
                  JokeRefreshing() => SelectableText(
                      '${state.currentJoke.setup}\n\n${state.currentJoke.punchline}',
                      textAlign: TextAlign.center,
                      style: const TextStyle(fontSize: 24),
                    ),
                  JokeError() => Text(
                      'Error fetching joke\n${state.message}',
                      textAlign: TextAlign.center,
                    ),
                  JokeInitial() || JokeLoading() => const CircularProgressIndicator(),
                },

                // 获取新笑话按钮
                Positioned(
                  bottom: 20,
                  child: ElevatedButton(
                    onPressed: () {
                      context.read<JokeBloc>().add(const RefreshJoke());
                    },
                    child: const Text('Get another joke'),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
